package reflect;

import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 调用与当前类Test10在同一个包中被注解@AutoRunClass标注的类中被@AutoRunMethod标注的方法
 * 指定次(次数由方法上注解@AutoRunMethod中指定的参数决定)
 */
public class Test10 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class c = Test10.class;
        String pack = c.getPackage().getName();

        File dir = new File(c.getResource(".").toURI());
        File[] files = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File f : files){
            String fName = f.getName().replace(".class","");

            Class cls = Class.forName(pack+"."+fName);

            Method[] methods = cls.getMethods();
            for (Method m : methods){
                if(m.isAnnotationPresent(AutoRunMethod.class)){
                    Object o = cls.newInstance();
                    AutoRunMethod arm = m.getAnnotation(AutoRunMethod.class);
                    int value = arm.value();
                    for (int i = 0; i < value; i++) {
                        m.invoke(o);
                    }
                }
            }
        }
    }
}
